package com.qiaofang.applet.rest;

import com.qiaofang.applet.common.context.QfContextHolder;
import com.qiaofang.applet.common.dto.DataRequest;
import com.qiaofang.applet.common.dto.DataResponse;
import com.qiaofang.applet.common.dto.PageDataRequest;
import com.qiaofang.applet.common.exception.BusinessException;
import com.qiaofang.applet.common.util.PageUtil;
import com.qiaofang.applet.constants.BusinessConstants;
import com.qiaofang.applet.constants.UpDownFlagConstants;
import com.qiaofang.applet.service.member.domain.Department;
import com.qiaofang.applet.service.member.domain.Employee;
import com.qiaofang.applet.service.member.domain.MemberFocus;
import com.qiaofang.applet.service.member.repository.DepartmentRepository;
import com.qiaofang.applet.service.member.service.EmployeeService;
import com.qiaofang.applet.service.member.service.MemberFocusService;
import com.qiaofang.applet.service.member.service.dto.*;
import com.qiaofang.applet.service.member.service.mapstruct.EmployeeMapper;
import com.qiaofang.applet.service.property.domain.Estate;
import com.qiaofang.applet.service.property.domain.FirsthandEstate;
import com.qiaofang.applet.service.property.domain.Property;
import com.qiaofang.applet.service.property.service.EstateService;
import com.qiaofang.applet.service.property.service.FirsthandEstateService;
import com.qiaofang.applet.service.property.service.PropertyService;
import com.qiaofang.applet.service.property.service.dto.*;
import com.qiaofang.applet.service.property.service.mapstruct.EstateMapper;
import com.qiaofang.applet.service.property.service.mapstruct.FirsthandEstateMapper;
import com.qiaofang.applet.service.property.service.mapstruct.PropertyMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author daiyuxaing
 */
@Slf4j
@RestController
@RequestMapping("/api/web/auth/memberFocus")
@Api(tags = "会员：会员关注")
public class MemberFocusController {

    @Autowired
    MemberFocusService memberFocusService;

    @Autowired
    PropertyService propertyService;

    @Autowired
    private FirsthandEstateService firsthandEstateService;

    @Autowired
    private PropertyMapper propertyMapper;

    @Autowired
    private FirsthandEstateMapper firsthandEstateMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EstateService estateService;

    @Autowired
    private EstateMapper estateMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private DepartmentRepository departmentRepository;

    @PostMapping("/searchFirsthandFocus")
    @ApiOperation(value = "查询关注新房记录", notes = "查询关注新房记录")
    public DataResponse<Page<FirsthandEstateListDto>> searchFirsthandFocus(@RequestBody @Valid PageDataRequest<IdDto> request) {
        Page<FirsthandEstateListDto> result = null;

        Pageable pageable = PageUtil.getPageable(request);
        MemberFocusQueryDto memberFocusQueryDto = new MemberFocusQueryDto();
        memberFocusQueryDto.setMemberId(request.getParam().getId());
        memberFocusQueryDto.setBusinessType(BusinessConstants.FIRSTHAND_ESTATE.getValue());

        Page<MemberFocus> memberFocusList = memberFocusService.findBusinessListByParams(memberFocusQueryDto, pageable);

        if (memberFocusList.getTotalElements() > 0) {
            List<String> uuidList = memberFocusList.stream().map(MemberFocus::getBusinessUuid).collect(Collectors.toList());

            FirsthandEstateQueryDto queryDto = new FirsthandEstateQueryDto();
            queryDto.setEstateUniqueUuids(uuidList.stream().distinct().collect(Collectors.toList()));
            queryDto.setUpDownFlag(UpDownFlagConstants.UP_FLAG.getValue());
            List<FirsthandEstate> propertyList = firsthandEstateService.findAllByParams(queryDto);

            Map<String, FirsthandEstateListDto> propertyMap = propertyList.stream()
                    .collect(Collectors.toMap(FirsthandEstate::getEstateUniqueUuid, firsthandEstateMapper::domainToListDto, (a1, a2) -> a2));
            result = new PageImpl<>(uuidList.stream().map(propertyMap::get).collect(Collectors.toList()), pageable, memberFocusList.getTotalElements());
        }

        return DataResponse.ok(result);
    }

    @PostMapping("/searchSaleFocus")
    @ApiOperation(value = "查询关注二手房记录", notes = "查询关注二手房记录")
    public DataResponse<Page<SalePropertyListDto>> searchSaleFocus(@RequestBody @Valid PageDataRequest<IdDto> request) {
        Page<SalePropertyListDto> result = null;

        Pageable pageable = PageUtil.getPageable(request);
        MemberFocusQueryDto memberFocusQueryDto = new MemberFocusQueryDto();
        memberFocusQueryDto.setMemberId(request.getParam().getId());
        memberFocusQueryDto.setBusinessType(BusinessConstants.SALE_PROPERTY.getValue());

        Page<MemberFocus> memberFocusList = memberFocusService.findBusinessListByParams(memberFocusQueryDto, pageable);

        if (memberFocusList.getTotalElements() > 0) {
            List<String> uuidList = memberFocusList.stream().map(MemberFocus::getBusinessUuid).collect(Collectors.toList());

            SalePropertyQueryDto queryDto = new SalePropertyQueryDto();
            queryDto.setPropertyUniqueUuids(uuidList.stream().distinct().collect(Collectors.toList()));
            queryDto.setUpDownFlag(UpDownFlagConstants.UP_FLAG.getValue());
            List<Property> propertyList = propertyService.findAllSaleByParams(queryDto);

            Map<String, SalePropertyListDto> propertyMap = propertyList.stream()
                    .collect(Collectors.toMap(Property::getPropertyUniqueUuid, propertyMapper::domainToSaleListDto, (a1, a2) -> a2));
            result = new PageImpl<>(uuidList.stream().map(propertyMap::get).collect(Collectors.toList()), pageable, memberFocusList.getTotalElements());
        }

        return DataResponse.ok(result);
    }

    @PostMapping("/searchRentFocus")
    @ApiOperation(value = "查询关注租房记录", notes = "查询关注租房记录")
    public DataResponse<Page<RentPropertyListDto>> searchRentFocus(@RequestBody @Valid PageDataRequest<IdDto> request) {
        Page<RentPropertyListDto> result = null;

        Pageable pageable = PageUtil.getPageable(request);
        MemberFocusQueryDto memberFocusQueryDto = new MemberFocusQueryDto();
        memberFocusQueryDto.setMemberId(request.getParam().getId());
        memberFocusQueryDto.setBusinessType(BusinessConstants.RENT_PROPERTY.getValue());

        Page<MemberFocus> memberFocusList = memberFocusService.findBusinessListByParams(memberFocusQueryDto, pageable);

        if (memberFocusList.getTotalElements() > 0) {
            List<String> uuidList = memberFocusList.stream().map(MemberFocus::getBusinessUuid).collect(Collectors.toList());

            RentPropertyQueryDto queryDto = new RentPropertyQueryDto();
            queryDto.setPropertyUniqueUuids(uuidList.stream().distinct().collect(Collectors.toList()));
            queryDto.setUpDownFlag(UpDownFlagConstants.UP_FLAG.getValue());
            List<Property> propertyList = propertyService.findAllRentByParams(queryDto);

            Map<String, RentPropertyListDto> propertyMap = propertyList.stream()
                    .collect(Collectors.toMap(Property::getPropertyUniqueUuid, propertyMapper::domainToRentListDto, (a1, a2) -> a2));
            result = new PageImpl<>(uuidList.stream().map(propertyMap::get).collect(Collectors.toList()), pageable, memberFocusList.getTotalElements());
        }

        return DataResponse.ok(result);
    }

    @PostMapping("/searchEmployeeFocus")
    @ApiOperation(value = "查询关注经纪人记录", notes = "查询关注经纪人记录")
    public DataResponse<Page<EmployeeListDto>> searchEmployeeFocus(@RequestBody @Valid PageDataRequest<IdDto> request) {
        Page<EmployeeListDto> result = null;

        Pageable pageable = PageUtil.getPageable(request);
        MemberFocusQueryDto memberFocusQueryDto = new MemberFocusQueryDto();
        memberFocusQueryDto.setMemberId(request.getParam().getId());
        memberFocusQueryDto.setBusinessType(BusinessConstants.EMPLOYEE.getValue());

        Page<MemberFocus> memberFocusList = memberFocusService.findBusinessListByParams(memberFocusQueryDto, pageable);

        if (memberFocusList.getTotalElements() > 0) {
            List<String> uuidList = memberFocusList.stream().map(MemberFocus::getBusinessUuid).collect(Collectors.toList());

            List<Employee> employeeList = employeeService.findAllByEmployeeUuidIn(QfContextHolder.getContext().getCorporationCode(), uuidList);
            //设置部门名称
            List<String> deptUuids = employeeList.stream().map(Employee::getDeptUuid).distinct().collect(Collectors.toList());
            List<Department> departmentList = departmentRepository.findListByDeptUuidInAndCorporationCode(deptUuids, QfContextHolder.getContext().getCorporationCode());
            if (!CollectionUtils.isEmpty(departmentList)) {
                for (Employee employee : employeeList) {
                    for (Department department : departmentList) {
                        if (StringUtils.equals(department.getDeptUuid(), employee.getDeptUuid())) {
                            employee.setDeptName(department.getDeptName());
                        }
                    }
                }
            }

            Map<String, EmployeeListDto> employeeListDtoMap = employeeList.stream()
                    .collect(Collectors.toMap(Employee::getEmployeeUniqueUuid, employeeMapper::domainToDto, (k1, k2) -> k2));

            result = new PageImpl<>(uuidList.stream().map(employeeListDtoMap::get).collect(Collectors.toList()), pageable, memberFocusList.getTotalElements());
        }

        return DataResponse.ok(result);
    }

    @PostMapping("/searchEstateFocus")
    @ApiOperation(value = "查询关注小区记录", notes = "查询关注小区记录")
    public DataResponse<Page<EstateListDto>> searchEstateFocus(@RequestBody @Valid PageDataRequest<IdDto> request) {
        Page<EstateListDto> result = null;

        Pageable pageable = PageUtil.getPageable(request);
        MemberFocusQueryDto memberFocusQueryDto = new MemberFocusQueryDto();
        memberFocusQueryDto.setMemberId(request.getParam().getId());
        memberFocusQueryDto.setBusinessType(BusinessConstants.ESTATE.getValue());

        Page<MemberFocus> memberFocusList = memberFocusService.findBusinessListByParams(memberFocusQueryDto, pageable);

        if (memberFocusList.getTotalElements() > 0) {
            List<String> uuidList = memberFocusList.stream().map(MemberFocus::getBusinessUuid).collect(Collectors.toList());

            EstateQueryDto estateQueryDto = new EstateQueryDto();
            estateQueryDto.setEstateUniqueUuids(uuidList.stream().distinct().collect(Collectors.toList()));
            List<Estate> estateList = estateService.findAllEstateByParams(estateQueryDto);

            Map<String, EstateListDto> estateMap = estateList.stream()
                    .collect(Collectors.toMap(Estate::getEstateUniqueUuid, estateMapper::domainToListDto, (a1, a2) -> a2));

            result = new PageImpl<>(uuidList.stream().map(estateMap::get).collect(Collectors.toList()), pageable, memberFocusList.getTotalElements());
        }
        return DataResponse.ok(result);
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加关注", notes = "添加关注")
    public DataResponse<Object> add(@RequestBody @Valid DataRequest<MemberFocusSaveDto> request) {


        MemberFocus params = new MemberFocus();
        BeanUtils.copyProperties(request.getParam(), params);
        params.setCreateTime(new Date());
        params.setCorporationCode(QfContextHolder.getContext().getCorporationCode());
        params.setCityCode(QfContextHolder.getContext().getCityCode());

        Boolean isFocus = memberFocusService.isExistsByMemberIdAndBusinessUuid(params.getMemberId(), params.getBusinessUuid(), params.getBusinessType());

        if (isFocus) {
            throw new BusinessException("已经关注");
        } else {
            memberFocusService.save(params);
        }


        return DataResponse.ok();
    }

    @PostMapping("/delete")
    @ApiOperation(value = "取消关注", notes = "取消关注")
    public DataResponse<Object> delete(@RequestBody @Valid DataRequest<MemberFocusSaveDto> request) {
        @NotNull(message = "请求参数不能为空") MemberFocusSaveDto param = request.getParam();
        memberFocusService.deleteByMemberIdAndBusinessUuidAndBusinessType(param.getMemberId(), param.getBusinessUuid(), param.getBusinessType());

        return DataResponse.ok();
    }


    @PostMapping("/isExists")
    @ApiOperation(value = "是否关注", notes = "是否关注")
    public DataResponse<Boolean> isExists(@RequestBody @Valid DataRequest<MemberFocusExistsDto> request) {
        return DataResponse.ok(memberFocusService.isExistsByMemberIdAndBusinessUuid(request.getParam().getMemberId(), request.getParam().getBusinessUuid(), request.getParam().getBusinessType()));
    }

}
